package org.javaboy.vhr.controller.system.basic;

import org.javaboy.vhr.model.Menu;
import org.javaboy.vhr.model.Role;
import org.javaboy.vhr.service.MenuService;
import org.javaboy.vhr.service.RoleService;
import org.javaboy.vhr.responseBean.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理
 */
@RestController
@RequestMapping("/system/basic/power")
public class PowerController {

    @Autowired
    RoleService powerService;
    @Autowired
    MenuService menuService;

    /**
     * 获取所有的角色
     * @return
     */
    @GetMapping("/")
    public ServerResponse getAllRole(){
        List<Role> roleList = powerService.getAllRole();
        return ServerResponse.success("",roleList);
    }

    /**
     * 获取菜单
     * @return
     */
    @GetMapping("menus")
    public ServerResponse getAllMenu(){
        List<Menu> menuList = menuService.getAllMenu();
        return ServerResponse.success("",menuList);
    }

    /**
     * 根据rid查询菜单的menuIds
     * @param rid
     * @return
     */
    @GetMapping("getMenuIdByRid/{rid}")
    public ServerResponse getMenuIdByRid(@PathVariable Integer rid){
        List<Integer> menuIds = menuService.getMenuIdByRid(rid);
        return ServerResponse.success("",menuIds);
    }

    /**
     * 修改角色访问的菜单
     * @param rid
     * @param mIds
     * @return
     */
    @PutMapping("/")
    public ServerResponse updatePowerByRid(Integer rid,Integer [] mIds){
        Boolean result = menuService.updatePowerByRid(rid,mIds);
        if(result){
            return ServerResponse.success("修改成功");
        }
        return ServerResponse.error(1000,"修改失败");
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @PostMapping("/")
    public ServerResponse addRole(@RequestBody Role role){
        if(!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        if(powerService.addRole(role)==1){
            return ServerResponse.success("添加成功");
        }
        return ServerResponse.error(1000,"添加失败");
    }

    @DeleteMapping("/{id}")
    public ServerResponse deleteRoleById(@PathVariable("id") Integer id){
        if(powerService.deleteRoleById(id)==1){
            return ServerResponse.success("删除成功");
        }
        return ServerResponse.error(1000,"删除失败");
    }
}
